package com.candy.candyshortlink.config;

import com.candy.candycommon.utils.ApplicationContentUtils;
import com.candy.candyshortlink.business.entity.ShortLink;
import com.candy.candyshortlink.business.service.IShortLinkService;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/12/27 13:17
 * @Description 描述
 */
public class UrlHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        IShortLinkService bean = ApplicationContentUtils.getBean(IShortLinkService.class);
        String requestURI = request.getRequestURI();
        if (requestURI.substring(1).contains("/")) {
            return true;
        }
        ShortLink shortLink = bean.getByShortUrl(requestURI.substring(1));

        if (shortLink == null) {
            // TODO 打印异常页面
            return false;
        }
        StringBuffer requestURL = request.getRequestURL();
        // TODO PV\UV统计
//        response.sendRedirect(shortLink.getSourceUrl());
        response.setStatus(301);
        response.setHeader("location", shortLink.getSourceUrl());
        return false;
    }

}
